package com.example.security.controller;

import com.example.security.entity.UserEntity;
import com.example.security.repository.UserRepository;
import com.example.security.security.JwtTokenProvider;
import com.example.security.security.SecurityUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

/**
 * @author : zhayh
 * @date : 2021-4-17 14:07
 * @description :
 */

@RestController
@RequestMapping("/api")
public class HelloController {
    private final UserRepository userRepository;

    public HelloController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    /**
     * 将/api/login生成的token字符串作为”Authorization“为关键字的查询参数或header（UserTokenFilter类）
     * @return
     */
    @GetMapping("/account")
    public ResponseEntity getAccount() {
        String login = SecurityUtils.getCurrentUserLogin().get();
        Optional<UserEntity> userEntityOpional = userRepository.findByLogin(login);
        if (userEntityOpional.isPresent()) {
            return ResponseEntity.ok(userEntityOpional.get());
        } else {
            return ResponseEntity.badRequest().body("未找到登录用户信息");
        }
    }

    @GetMapping("/")
    public ResponseEntity<String> hello() {
        return ResponseEntity.ok("hello security");
    }

    @GetMapping("/admin/hello")
    public ResponseEntity<String> admin() {
        return ResponseEntity.ok("hello admin");
    }

    @GetMapping("/user/hello")
    public ResponseEntity<String> user() {
        return ResponseEntity.ok("hello user");
    }

}
